<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      v-loading="formLoading"
      :model="dataForm"
      :rules="dataRule"
      inline=""
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
    >
      <el-form-item
        label="用户名"
        prop="userName"
      >
        <el-input
          v-model="dataForm.userName"
          placeholder="登录帐号"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="姓名"
        prop="name"
      >
        <el-input
          v-model="dataForm.name"
          placeholder="姓名"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="所属部门"
        prop="deptId"
      >
        <el-input
          v-model="dataForm.deptName"
          v-popover:deptListPopover
          :readonly="true"
          placeholder="点击选择所属部门"
          class="menu-list__input"
        ></el-input>
        <el-popover
          ref="deptListPopover"
          placement="bottom-start"
          trigger="click"
        >
          <el-tree
            :data="deptList"
            :props="deptListTreeProps"
            node-key="id"
            show-checkbox
            ref="deptListTree"
            @check-change="checkChange"
            @node-click="nodeClick"
            :check-strictly="true"
            :default-expand-all="true"
            :highlight-current="true"
            :expand-on-click-node="false"
          >
          </el-tree>
        </el-popover>
      </el-form-item>
      <el-form-item
        label="密码"
        prop="password"
        :class="{ 'is-required': !dataForm.id }"
      >
        <el-input
          v-model="dataForm.password"
          type="password"
          placeholder="密码"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="确认密码"
        prop="comfirmPassword"
        :class="{ 'is-required': !dataForm.id }"
      >
        <el-input
          v-model="dataForm.comfirmPassword"
          type="password"
          placeholder="确认密码"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="邮箱"
        prop="email"
      >
        <el-input
          v-model="dataForm.email"
          placeholder="邮箱"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="手机号"
        prop="mobile"
      >
        <el-input
          v-model="dataForm.mobile"
          placeholder="手机号"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="座机号"
        prop="tel"
      >
        <el-input
          v-model="dataForm.tel"
          placeholder="座机号"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="身份证"
        prop="idCard"
      >
        <el-input
          v-model="dataForm.idCard"
          placeholder="身份证"
        ></el-input>
      </el-form-item>


      <el-form-item
        label="状态"
        size="mini"
        prop="status"
      >
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="0">禁用</el-radio>
          <el-radio :label="1">正常</el-radio>
        </el-radio-group>
      </el-form-item><br>
      <el-form-item label="角色" prop="roleIdList">
        
         <el-select v-model="dataForm.roleIdList" multiple placeholder="请选择" style="width:470px">
          <el-option
            v-for="role in roleList"
            :key="role.id"
            :label="role.roleName"
            :value="role.id">
          </el-option>
        </el-select>

        <!-- <el-checkbox-group v-model="dataForm.roleIdList">
          <el-checkbox
            v-for="role in roleList"
            :key="role.id"
            :label="role.id"
          >{{ role.roleName }}</el-checkbox>
        </el-checkbox-group> -->

      </el-form-item>
    </el-form>
    <span
      slot="footer"
      class="dialog-footer"
    >
      <el-button @click="visible = false">取消</el-button>
      <el-button
        type="primary"
        v-loading="formLoading"
        @click="dataFormSubmit()"
      >确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import { treeDataTranslate } from '@/utils'
  import { isEmail, isMobile } from '@/utils/validate'
  import { debug } from 'util';
  export default {
    data () {
      var validatePassword = (rule, value, callback) => {
        if (!this.dataForm.id && !/\S/.test(value)) {
          callback(new Error('密码不能为空'))
        } else {
          callback()
        }
      }
      var validateComfirmPassword = (rule, value, callback) => {
        if (!this.dataForm.id && !/\S/.test(value)) {
          callback(new Error('确认密码不能为空'))
        } else if (this.dataForm.password !== value) {
          callback(new Error('确认密码与密码输入不一致'))
        } else {
          callback()
        }
      }
      var validateEmail = (rule, value, callback) => {
        if (!isEmail(value)) {
          callback(new Error('邮箱格式错误'))
        } else {
          callback()
        }
      }
      var validateMobile = (rule, value, callback) => {
        if (!isMobile(value)) {
          callback(new Error('手机号格式错误'))
        } else {
          callback()
        }
      }
      return {
        visible: false,
        formLoading: false,
        roleList: [],
        dataForm: {
          id: 0,
          userName: '',
          password: '',
          comfirmPassword: '',
          salt: '',
          email: '',
          mobile: '',
          roleIdList: [],
          status: 1,
          deptName: ''
        },
        dataRule: {
          userName: [
            { required: true, message: '用户名不能为空', trigger: 'blur' }
          ],
          password: [
            { validator: validatePassword, trigger: 'blur' }
          ],
          comfirmPassword: [
            { validator: validateComfirmPassword, trigger: 'blur' }
          ],
          email: [
            { required: true, message: '邮箱不能为空', trigger: 'blur' },
            { validator: validateEmail, trigger: 'blur' }
          ],
          mobile: [
            { required: true, message: '手机号不能为空', trigger: 'blur' },
            { validator: validateMobile, trigger: 'blur' }
          ],
          deptId: [
            { required: true, message: '所属部门不能为空', trigger: 'change' }
          ]
        },
        deptList: [],
        deptListTreeProps: {
          label: 'name',
          children: 'children'
        }
      }
    },
    methods: {
      init (id,deptId) {
        this.dataForm.id = id || 0
        // 初始化部门树
        this.$http({
          url: this.$http.adornUrl('/sys/dept/list'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          this.deptList = treeDataTranslate(data, 'id')
        })

         
        this.$http({
          url: this.$http.adornUrl('/sys/role/select'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          this.roleList = data && data.code === 0 ? data.list : []
        }).then(() => {
          this.visible = true
          this.formLoading = false
          this.$nextTick(() => {
            this.$refs['dataForm'].resetFields()
          })
        }).then(() => {
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/sys/user/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.userName = data.user.username
                this.dataForm.salt = data.user.salt
                this.dataForm.email = data.user.email
                this.dataForm.name = data.user.name
                this.dataForm.tel = data.user.tel
                this.dataForm.idCard = data.user.idCard
                this.dataForm.mobile = data.user.mobile
                this.dataForm.status = data.user.status
                this.dataForm.deptId = data.user.deptId
                this.dataForm.version = data.user.version
                this.dataForm.roleIdList = data.user.roleIdList
                this.deptListTreeSetCurrentNode()
              }
            })
          }else{// 新增
            this.dataForm= {
                id: 0,
                userName: '',
                password: '',
                comfirmPassword: '',
                salt: '',
                email: '',
                mobile: '',
                roleIdList: [],
                status: 1,
                deptName: '',
                deptId:deptId
            }
            if(deptId){
              this.deptListTreeSetCurrentNode()
            }
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid && !this.formLoading) {
            this.formLoading = true
            this.$http({
              url: this.$http.adornUrl(`/sys/user/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'username': this.dataForm.userName,
                'password': this.dataForm.password,
                'salt': this.dataForm.salt,
                'email': this.dataForm.email,
                'mobile': this.dataForm.mobile,
                'status': this.dataForm.status,
                'version': this.dataForm.version,
                'name': this.dataForm.name,
                'tel': this.dataForm.tel,
                'idCard': this.dataForm.idCard,
                'deptId': this.dataForm.deptId,
                'roleIdList': this.dataForm.roleIdList
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.formLoading = false
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      // 菜单树设置当前选中节点
      deptListTreeSetCurrentNode () {
        this.$refs.deptListTree.setChecked(this.dataForm.deptId,true,false)
        this.dataForm.deptName = (this.$refs.deptListTree.getCheckedNodes() || [])[0].name

      },
      // 节点修改
      checkChange(data, checked, node){
          if(checked == true){// 选中部门
              this.checkedId = data.id;
              this.$refs.deptListTree.setCheckedNodes([data]);

              this.dataForm.deptId = data.id
              this.dataForm.deptName = data.name
          }
      },
      nodeClick(data,checked,node){
          this.checkedId = data.id
          this.$refs.deptListTree.setCheckedNodes([data]);
      }

    }
  }
</script>
